<?php if(!class_exists("View", false)) exit("no direct access allowed");?><main class="container mx-auto px-4 pt-24 pb-16 flex">
    <?php include $_view_obj->compile("left_menu.html"); ?>

    <!-- 应用列表 -->
    <section class="mb-10 w-3/4 ml-4 bg-white rounded-xl shadow-sm p-4">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-dark">权限列表</h2>

            <div class="flex items-center space-x-4" id="user-info">
                <button class="btn btn-primary" id="add-app-button">
                    <i class="fa fa-plus"></i>
                    新增权限分组
                </button>
            </div>
        </div>
        <!-- 新增说明提示 -->
        <div class="text-gray-600 text-sm text-warning">
            本页面用于管理权限分组，您可以新增、编辑、删除权限分组，还可以配置分组的模块权限。点击“新增权限分组”按钮可创建新的分组，点击“模块权限”按钮可配置分组的模块权限。
        </div>

        <!--新增滚动容器-->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            ID
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            应用名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            分组名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider max-w-40">
                            分组描述
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            用户列表
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody id="app-list" class="bg-white divide-y divide-gray-200">
                </tbody>
            </table>
        </div>
        <div class="flex justify-center mt-4" id="pagination">
        </div>

    </section>

</main>

<!-- 新增应用弹窗 -->
<div id="add-app-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-3xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">新增权限组</h2>
        <form id="add-app-form">
            <div class="mb-6">
                <label for="add-app-name" class="block text-sm font-medium text-gray-700">应用名称</label>
                <select id="add-app-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
                    <!-- 选项将通过接口填充 -->
                </select>
            </div>
            <div class="mb-6">
                <label for="add-group-name" class="block text-sm font-medium text-gray-700">分组名称</label>
                <input type="text" id="add-group-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="add-group-desc" class="block text-sm font-medium text-gray-700">分组描述</label>
                <textarea id="add-group-desc" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"></textarea>
            </div>
            <div class="flex justify-end">
                <button type="button" class="btn btn-secondary mr-2" onclick="closeAddAppModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 编辑应用弹窗 -->
<div id="edit-app-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-3xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">编辑分组</h2>
        <form id="edit-app-form">
            <input type="hidden" id="edit-app-id">
            <div class="mb-6">
                <label for="edit-app-name" class="block text-sm font-medium text-gray-700">应用名称</label>
                <select id="edit-app-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
                    <!-- 选项将通过接口填充 -->
                </select>
            </div>
            <div class="mb-6">
                <label for="edit-group-name" class="block text-sm font-medium text-gray-700">分组名称</label>
                <input type="text" id="edit-group-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="edit-group-desc" class="block text-sm font-medium text-gray-700">分组描述</label>
                <textarea id="edit-group-desc" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"></textarea>
            </div>
            <div class="flex justify-end">
                <button type="button" class="btn btn-secondary mr-2" onclick="closeEditAppModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 模块权限配置弹窗 -->
<div id="module-permission-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-3xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">模块权限配置</h2>
        <form id="module-permission-form">
            <input type="hidden" id="module-group-id">
            <div id="module-list" class="mb-6">
                <!-- 模块列表将通过接口填充 -->
            </div>
            <div class="flex justify-end">
                <button type="button" class="btn btn-secondary mr-2" onclick="closeModulePermissionModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<style>
    /* 分组描述字段样式 */
   .max-w-40 {
        max-width: 200px; /* 设置最大宽度 */
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

   .max-w-40:hover {
        white-space: normal;
        overflow: visible;
        text-overflow: clip;
    }

    /* 用户列表标签样式 */
   .user-tag {
        display: inline-block;
        background-color: #e2e8f0;
        color: #4a5568;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        margin: 0.125rem;
    }

    /* 分页按钮样式 */
   .pagination-btn {
        display: inline-block;
        padding: 0.5rem 1rem;
        margin: 0 0.25rem;
        border: 1px solid #ddd;
        border-radius: 0.25rem;
        background-color: #fff;
        color: #007bff;
        text-decoration: none;
        cursor: pointer;
    }

   .pagination-btn:hover {
        background-color: #f0f0f0;
    }

   .pagination-btn.active {
        background-color: #007bff;
        color: #fff;
        border-color: #007bff;
    }
</style>

<script>
    let currentPage = 1;
    const itemsPerPage = 10; // 每页显示的记录数

    $(document).ready(function () {
        // 获取列表
        function getPermissionList(page) {
            $.ajax({
                url: '<?php echo url(array('c'=>"system", 'a'=>"GetPermissionList", ));?>',
                method: 'GET',
                data: {
                    page: page,
                    limit: itemsPerPage
                },
                success: function (response) {
                    fillPermissionList(response.data.list);
                    setupPagination(response.data.pager.total_page, page);
                },
                error: function (error) {
                    console.error('获取权限列表失败:', error);
                }
            });
        }

        // 填充列表
        function fillPermissionList(data) {
            const appList = $('#app-list');
            appList.empty();
            data.forEach(function (item) {
                const userList = item.realname.split(',').map(user => `<span class="user-tag">${user}</span>`).join('');
                const row = `
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">${item.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${item.app}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${item.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap max-w-40" title="${item.desc}">${item.desc}</td>
                        <td class="px-6 py-4">${userList}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button class="btn btn-black" onclick="openModulePermissionModal(${item.id})">模块权限</button>
                            <button class="btn btn-warning mr-2" onclick="openEditAppModal(${item.id}, '${item.app}', '${item.name}', '${item.desc}')">编辑</button>
                            <button class="btn btn-danger" onclick="deletePermissionGroup(${item.id})">删除</button>
                        </td>
                    </tr>
                `;
                appList.append(row);
            });
        }

        // 设置分页
        function setupPagination(totalPages, currentPage) {
            const pagination = $('#pagination');
            pagination.empty();

            for (let i = 1; i <= totalPages; i++) {
                const pageButton = `<button class="pagination-btn ${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
                pagination.append(pageButton);
            }
        }

        // 切换页码
        window.changePage = function (page) {
            currentPage = page;
            getPermissionList(page);
        };

        // 获取应用列表
        function getAppList(selectId, selectedValue = '') {
            $.ajax({
                url: '<?php echo url(array('c'=>"system", 'a'=>"GetApps", ));?>', // 替换为实际的接口地址
                method: 'GET',
                success: function (response) {
                    const select = $(`#${selectId}`);
                    select.empty();
                    response.data.forEach(function (app) {
                        const option = `<option value="${app.id}" ${app.id === selectedValue ? 'selected' : ''}>${app.appName}</option>`;
                        select.append(option);
                    });
                },
                error: function (error) {
                    console.error('获取应用列表失败:', error);
                }
            });
        }

        // 新增分组
        $('#add-app-form').on('submit', function (e) {
            e.preventDefault();
            const appId = $('#add-app-name').val();
            const groupName = $('#add-group-name').val();
            const groupDesc = $('#add-group-desc').val();

            $.ajax({
                url: '<?php echo url(array('c'=>"system", 'a'=>"GroupAdd", ));?>',
                method: 'POST',
                data: {
                    app: appId,
                    name: groupName,
                    desc: groupDesc
                },
                success: function (response) {
                    closeAddAppModal();
                    getPermissionList(currentPage);
                },
                error: function (error) {
                    console.error('新增权限分组失败:', error);
                }
            });
        });

        // 编辑分组
        window.openEditAppModal = function (id, appId, groupName, groupDesc) {
            $('#edit-app-id').val(id);
            getAppList('edit-app-name', appId);
            $('#edit-group-name').val(groupName);
            $('#edit-group-desc').val(groupDesc);
            $('#edit-app-modal').removeClass('hidden');
        };

        $('#edit-app-form').on('submit', function (e) {
            e.preventDefault();
            const id = $('#edit-app-id').val();
            const appId = $('#edit-app-name').val();
            const groupName = $('#edit-group-name').val();
            const groupDesc = $('#edit-group-desc').val();

            $.ajax({
                url: '<?php echo url(array('c'=>"system", 'a'=>"UpdateGroup", ));?>',
                method: 'POST',
                data: {
                    id: id,
                    app_id: appId,
                    group_name: groupName,
                    group_desc: groupDesc
                },
                success: function (response) {
                    closeEditAppModal();
                    getPermissionList(currentPage);
                },
                error: function (error) {
                    console.error('编辑权限分组失败:', error);
                }
            });
        });

        // 删除分组
        window.deletePermissionGroup = function (id) {
            if (confirm('确定要删除这个权限分组吗？')) {
                $.ajax({
                    url: '<?php echo url(array('c'=>"system", 'a'=>"DelGroup", ));?>',
                    method: 'POST',
                    data: { id: id },
                    success: function (response) {
                        getPermissionList(currentPage);
                    },
                    error: function (error) {
                        console.error('删除权限分组失败:', error);
                    }
                });
            }
        };

        // 打开新增分组弹窗
        $('#add-app-button').on('click', function () {
            getAppList('add-app-name');
            $('#add-app-modal').removeClass('hidden');
        });

        // 关闭新增分组弹窗
        window.closeAddAppModal = function () {
            $('#add-app-modal').addClass('hidden');
            $('#add-app-form')[0].reset();
        };

        // 关闭编辑分组弹窗
        window.closeEditAppModal = function () {
            $('#edit-app-modal').addClass('hidden');
            $('#edit-app-form')[0].reset();
        };

        // 打开模块权限配置弹窗
        // 打开模块权限配置弹窗
        window.openModulePermissionModal = function (groupId) {
            $('#module-group-id').val(groupId);
            // 获取模块列表
            $.ajax({
                url: '<?php echo url(array('c'=>"system", 'a'=>"GetGroupPriv", ));?>', // 替换为实际的接口地址
                method: 'GET',
                data: { group_id: groupId },
                success: function (response) {
                    const moduleList = $('#module-list');
                    moduleList.empty();
                    // 检查 response.data.acl 是否为数组，如果不是则初始化为空数组
                    const acl = response.data.acl || []; 
                    const aclIds = acl.map(item => item.id);
                    response.data.apps.forEach(function (app) {
                        const isChecked = aclIds.includes(app.id);
                        const moduleCheckbox = `
                            <div class="flex items-center mb-2">
                                <input type="checkbox" id="module-${app.id}" name="modules[]" value="${app.id}" class="form-checkbox h-5 w-5 text-primary" ${isChecked ? 'checked' : ''}>
                                <label for="module-${app.id}" class="ml-2 text-gray-700">${app.moduleName}</label>
                            </div>
                        `;
                        moduleList.append(moduleCheckbox);
                        app.childs.forEach(function (child) {
                            const childIsChecked = aclIds.includes(child.id);
                            const childCheckbox = `
                                <div class="flex items-center mb-2 ml-6">
                                    <input type="checkbox" id="module-${child.id}" name="modules[]" value="${child.id}" class="form-checkbox h-5 w-5 text-primary" ${childIsChecked ? 'checked' : ''}>
                                    <label for="module-${child.id}" class="ml-2 text-gray-700">${child.methodName}</label>
                                </div>
                            `;
                            moduleList.append(childCheckbox);
                        });
                    });
                    $('#module-permission-modal').removeClass('hidden');
                },
                error: function (error) {
                    console.error('获取模块列表失败:', error);
                }
            });
        };

        // 关闭模块权限配置弹窗
        window.closeModulePermissionModal = function () {
            $('#module-permission-modal').addClass('hidden');
            $('#module-permission-form')[0].reset();
        };

        // 保存模块权限配置
        $('#module-permission-form').on('submit', function (e) {
            e.preventDefault();
            const groupId = $('#module-group-id').val();
            const selectedModules = $('input[name="modules[]"]:checked').map(function () {
                return this.value;
            }).get();

            // 将选中的模块 ID 数组转换为逗号分隔的字符串
            const acl = selectedModules.join(',');

            $.ajax({
                url: '<?php echo url(array('c'=>"system", 'a'=>"GroupprivUp", ));?>', // 替换为实际的接口地址
                method: 'POST',
                data: {
                    groupid: groupId,
                    acl: acl
                },
                success: function (response) {
                    closeModulePermissionModal();
                    getPermissionList(currentPage);
                },
                error: function (error) {
                    console.error('保存模块权限配置失败:', error);
                }
            });
        });

        // 初始化获取列表
        getPermissionList(currentPage);
    });
</script>